`
https://leetcode.cn/problems/smallest-subtree-with-all-the-deepest-nodes/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var subtreeWithAllDeepest = function (root) {
  // 函数定义：返回以 root 为根节点的子树的最大深度
  const traverse = (node) => {
    // base case
    if (node === null) return { depth: 0, node: null }

    // 后序遍历
    const left = traverse(node.left)
    const right = traverse(node.right)

    // 返回深度更大的节点
    if (left.depth === right.depth) {
      return { depth: left.depth + 1, node: node }
    } else if (left.depth > right.depth) {
      return { depth: left.depth + 1, node: left.node }
    } else {
      return { depth: right.depth + 1, node: right.node }
    }
  };

  return traverse(root).node;
};